<template>
  <div id="panel">
    <template>
      <el-card class="queryForm">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          :label-position="'right'"
        >
          <el-form-item label="点位名称：" prop="segmentname">
            <el-input
              v-model="queryParams.segmentname"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="入河排口名称：" prop="rhoutfallid" class="times">
            <el-select v-model="queryParams.rhoutfallid" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <div class="searchBtnBox">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              style="padding: 10px"
              >查询</el-button
            >
            <el-button @click="resetQuery" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              清除
            </el-button>
          </div>
        </el-form>
      </el-card>
      <el-card class="pageContent">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="tableList.rows"
          stripe
          :height="tableHeight"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" />
          <el-table-column prop="segmentname" label="点位名称" />
          <el-table-column prop="name" label="点位类型">
            <template slot-scope="scope">
              {{ seltypeRow(scope.row.isauto, scope.row.ismanual) }}
            </template>
          </el-table-column>
          <el-table-column prop="rhoutfallname" label="入河排污口名称" />
          <el-table-column prop="upstreamordownstream" label="上下游关系" />
          <el-table-column prop="describe" label="描述" />
          <el-table-column fixed="right" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="edit(scope.row)">编辑</el-button>
              <el-button type="text" @click="delRows(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagination-self"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :pager-count="5"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="slot, total, sizes, prev, pager, next, jumper"
          :total="tableList.total"
        >
          <el-button
            class="refresh-button"
            icon="el-icon-refresh"
            title="刷新"
            @click="getList"
          />
        </el-pagination>
      </el-card>
    </template>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="点位类型">
              <el-radio-group
                v-model="seltype"
                :disabled="!isAdd"
                @change="CheckChange"
                class="radio-group"
              >
                <el-radio :disabled="!isAdd" label="0">自动</el-radio>
                <el-radio :disabled="!isAdd" label="1">手工</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="点位名称" prop="segmentid">
              <el-select
                v-model="form.segmentid"
                placeholder="请选择"
                style="width: 100%"
                @change="handleSelectChange"
              >
                <el-option
                  v-for="item in dmlist"
                  :key="item.id"
                  :label="item.segmentname"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入河排口名称" prop="rhoutfallid">
              <el-select
                v-model="form.rhoutfallid"
                placeholder="请选择"
                style="width: 100%"
                @change="handleSelectChangeRiver"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上下游关系" prop="upstreamordownstream">
              <el-select
                clearable
                v-model="form.upstreamordownstream"
                placeholder="请选择上下游关系"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.sys_updown"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="describe">
              <el-input
                v-model="form.describe"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDmRoutfallList,
  getDmRoutfallDetail,
  updateDmRoutfall,
  addDmRoutfall,
  deleteDmRoutfall,
  getRoutfallSelect,
  getDmList,
} from "@/api/dataResources/monitorData/section.js";
import { download } from "@/utils/request.js";
export default {
  name: "HydrologicStation",
  dicts: ["sys_updown"],
  components: {},
  data() {
    return {
      // 选中数组
      ids: [],
      tableHeight: window.innerHeight - 400,
      options: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        segmentname: "",
        rhoutfallid: "",
      },
      tableList: {
        total: 0,
        rows: [],
      },
      dateRange: [],
      tableData: [
        {
          date: "2016-05-02",
          name: "绿萃厂界",
          province: "2.52",
          lhq: "-",
          an: "-",
          voc: "0.250",
          fx: "东北偏东风",
          sd: "-",
          dqy: "-",
          ou: "-",
          swwd: "19.88",
          city: "普陀区",
          address: "上海市普陀区金沙江路 1518 弄",
          zip: 200333,
        },
      ],
      // 是否显示新增/修改弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        segmentid: [
          { required: true, message: "点位名称不能为空", trigger: "change" },
        ],
        rhoutfallid: [
          {
            required: true,
            message: "入河排口名称不能为空",
            trigger: "change",
          },
        ],
        upstreamordownstream: [
          { required: true, message: "上下游关系不能为空", trigger: "change" },
        ],
      },
      // 点位下拉列表
      seltype: "",
      dmlist: [],
      isauto: "", // 是否自动监测
      ismanual: "", // 是否手工监测
      // 是否新增操作项
      isAdd: false,
    };
  },
  created() {
    this.getRhpwk();
  },
  mounted() {
    this.pageInit();
  },
  methods: {
    // 页面初始化请求的数据
    pageInit() {
      this.getList();
    },
    // 格式化点位类型显示
    seltypeRow(a, b) {
      if (a === "1") {
        return "自动";
      } else if (b === "1") {
        return "手工";
      } else {
        return "";
      }
    },
    // 获取入河排口下拉选项数据
    getRhpwk() {
      getRoutfallSelect()
        .then((response) => {
          this.options = response.data.map((item) => ({
            value: item.id,
            label: item.outfallname,
          }));
        })
        .catch((error) => {
          this.$message.error("获取入河排口数据失败: " + error.message);
        });
    },
    // 获取点位下拉列表
    getDmList() {
      let params = {
        pageNum: 1,
        pageSize: 1000,
        isauto: this.isauto,
        ismanual: this.ismanual,
        isdrink: "0",
      };
      getDmList(params)
        .then((response) => {
          this.dmlist = response.rows || [];
        })
        .catch((error) => {
          this.$message.error("获取点位数据失败: " + error.message);
        });
    },
    // 表格checkbox选择数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    /** 新增按钮操作 - 核心改造点 */
    handleAdd() {
      this.reset();
      this.isAdd = true;
      this.open = true;
      this.title = "添加";
      // 1. 新增时默认选中"自动"类型
      this.seltype = "0";
      // 2. 设置自动站参数
      this.isauto = "1";
      this.ismanual = "";
      // 3. 自动加载自动站类型的点位列表
      this.getDmList();
    },
    /** 修改按钮操作 */
    handleUpdate() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条数据");
        return;
      }
      const row = this.tableList.rows.find((item) => item.id === this.ids[0]);
      if (row) {
        this.edit(row);
      }
    },
    /** 删除按钮操作 */
    handleDelete() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条数据");
        return;
      }
      const userIds = this.ids.join(",");
      this.$modal
        .confirm(`是否确认删除选中的${this.ids.length}条数据？`)
        .then(() => {
          return deleteDmRoutfall(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.ids = [];
        })
        .catch(() => {});
    },
    // 行间编辑
    edit(row) {
      this.reset();
      this.isAdd = false;
      this.title = "修改";
      // 设置点位类型
      this.seltype = row.isauto === "1" ? "0" : row.ismanual === "1" ? "1" : "";
      this.isauto = row.isauto;
      this.ismanual = row.ismanual;
      this.getDmList();
      // 获取详情
      getDmRoutfallDetail(row.id)
        .then((response) => {
          this.form = response.data || {};
          this.open = true;
        })
        .catch((error) => {
          this.$message.error("获取数据详情失败: " + error.message);
        });
    },
    // 删除行
    delRows(row) {
      this.$modal
        .confirm("是否确认删除该数据项？")
        .then(() => {
          return deleteDmRoutfall(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 选择类型变化
    CheckChange(e) {
      if (e === "0") {
        this.isauto = "1";
        this.ismanual = "";
      } else if (e === "1") {
        this.isauto = "";
        this.ismanual = "1";
      }
      this.getDmList();
      // 清空已选点位，避免类型不匹配
      this.form.segmentid = "";
      this.form.segmentname = "";
    },
    // 分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置、清除表单
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.resetFields();
      this.getList();
    },
    // 弹出层取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 监听选中点位下拉列表的变化
    handleSelectChange(selectedId) {
      const selectedItem = this.dmlist.find((item) => item.id === selectedId);
      if (selectedItem) {
        this.isauto = selectedItem.isauto;
        this.ismanual = selectedItem.ismanual;
        this.form.segmentname = selectedItem.segmentname;
      }
    },
    // 监听入河排口下拉列表的变化
    handleSelectChangeRiver(selectedId) {
      const selectedItem = this.options.find(
        (item) => item.value === selectedId
      );
      if (selectedItem) {
        this.form.rhoutfallname = selectedItem.label;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        segmentname: "",
        segmentid: "",
        rhoutfallname: "",
        rhoutfallid: "",
        upstreamordownstream: "",
        describe: "",
      };
      this.isauto = "";
      this.ismanual = "";
      this.seltype = "";
      this.dmlist = [];
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 补充点位类型参数
          this.form.isauto = this.seltype === "0" ? "1" : "0";
          this.form.ismanual = this.seltype === "1" ? "1" : "0";

          if (this.form.id) {
            updateDmRoutfall(this.form)
              .then(() => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch((error) => {
                this.$message.error("修改失败: " + error.message);
              });
          } else {
            addDmRoutfall(this.form)
              .then(() => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch((error) => {
                this.$message.error("新增失败: " + error.message);
              });
          }
        }
      });
    },
    // 导出
    handleExport() {
      let params = {};
      download(
        "/base/segmentorrhoutfall/export",
        params,
        "点位与入河排污口信息.xlsx"
      );
    },
    // 获取表格数据
    getList() {
      getDmRoutfallList(this.queryParams)
        .then((response) => {
          this.tableList.total = response.total;
          this.tableList.rows = response.rows || [];
        })
        .catch((error) => {
          this.$message.error("获取数据失败: " + error.message);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 10px 0 10px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
</style>
